import { Role } from "../router/types";
import { useUserStore } from "../stores/userStore";

export interface User {
  id: string;
  username: string;
  roles: Role[];
  permissions: string[];
  avatar?: string;
}

class AuthService {
  /**
   * 登录
   */
  async login(username: string, password: string): Promise<User> {
    // 实际项目中，这里应该是一个API调用
    return new Promise((resolve, reject) => {
      // 模拟API调用
      setTimeout(() => {
        if (username === "admin" && password === "password") {
          const user: User = {
            id: "1",
            username: "admin",
            roles: ["admin"],
            permissions: ["all:read", "all:write", "dashboard:access"],
          };

          // 使用Zustand存储用户信息
          useUserStore.getState().setUser({
            id: user.id,
            username: user.username,
            roles: user.roles,
            permissions: user.permissions,
            token: `mock-jwt-token-${Date.now()}`, // 模拟JWT token
          });

          resolve(user);
        } else if (username === "user" && password === "password") {
          const user: User = {
            id: "2",
            username: "user",
            roles: ["user"],
            permissions: ["dashboard:read", "profile:read", "profile:write"],
          };

          // 使用Zustand存储用户信息
          useUserStore.getState().setUser({
            id: user.id,
            username: user.username,
            roles: user.roles,
            permissions: user.permissions,
            token: `mock-jwt-token-${Date.now()}`, // 模拟JWT token
          });

          resolve(user);
        } else {
          reject(new Error("用户名或密码不正确"));
        }
      }, 300);
    });
  }

  /**
   * 登出
   */
  logout(): void {
    // 使用Zustand清除用户信息
    useUserStore.getState().clearUser();
  }

  /**
   * 获取当前用户
   */
  getUser(): User | null {
    const state = useUserStore.getState();
    if (!state.isAuthenticated || !state.id) return null;

    return {
      id: state.id,
      username: state.username || "",
      roles: state.roles,
      permissions: state.permissions,
      avatar: state.avatar,
    };
  }

  /**
   * 判断用户是否已认证
   */
  getIsAuthenticated(): boolean {
    return useUserStore.getState().isAuthenticated;
  }

  /**
   * 判断用户是否有角色
   */
  hasRole(role: Role | Role[]): boolean {
    const state = useUserStore.getState();
    if (!state.isAuthenticated) return false;

    // Admin角色拥有所有权限
    if (state.roles.includes("admin")) return true;

    if (Array.isArray(role)) {
      return role.some((r) => state.roles.includes(r));
    }

    return state.roles.includes(role);
  }

  /**
   * 判断用户是否有权限
   */
  hasPermission(permission: string | string[]): boolean {
    const state = useUserStore.getState();
    if (!state.isAuthenticated) return false;

    // Admin角色拥有所有权限
    if (state.roles.includes("admin")) return true;

    if (Array.isArray(permission)) {
      return permission.some((p) => state.permissions.includes(p));
    }

    return state.permissions.includes(permission);
  }

  /**
   * 更新用户信息
   */
  updateUserInfo(userData: Partial<User>): void {
    useUserStore.getState().updateUser(userData);
  }
}

export const authService = new AuthService();
export default authService;
